package com.wenkang.stu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenkang.stu.enums.ExceptionEnums;
import com.wenkang.stu.exception.KangException;
import com.wenkang.stu.mapper.UserMapper;
import com.wenkang.stu.mapper.UserRoleMapper;
import com.wenkang.stu.pojo.SysUser;
import com.wenkang.stu.pojo.SysUserRole;
import com.wenkang.stu.vo.PageResult;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@Service
public class SysUserService extends ServiceImpl<UserMapper, SysUser> implements IService<SysUser> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    public SysUser selectByUsername(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    public PageResult<SysUser> selectByPage(Integer page, Integer pageSize, String search, Boolean[] desc, String[] sortBy) {
        // 封装分页条件
        Page<SysUser> pageWrapper = new Page<>(page, pageSize);
        // 封装查询条件
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        // 模糊搜索
        if (StringUtils.isNotBlank(search)) {
            queryWrapper.like("username", search).or().like("nickname", search);
        }
        // 排序
        if (ArrayUtils.isNotEmpty(sortBy)) {
            for (int i = 0; i < sortBy.length; i++) {
                queryWrapper.orderBy(true, desc[i], sortBy[i]);
            }
        } else {
            queryWrapper.orderByDesc("created");
        }
        Page<SysUser> userPage = userMapper.selectPage(pageWrapper, queryWrapper);
        return new PageResult<>(userPage.getTotal(), userPage.getPages(), userPage.getRecords());
    }

    @Transactional
    public void updateUser(SysUser user) {
        // 更新用户
        if (userMapper.updateById(user) == 0) {
            throw new KangException(ExceptionEnums.UPDATE_ERROR);
        }
        // 更新角色
        // 1、清除所有角色
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        userRoleMapper.delete(queryWrapper.eq("user_id", user.getId()));
        // 2、判断角色ids是否为空
        if (CollectionUtils.isEmpty(user.getRoleIds())) {
            // 更新成功
            return;
        }
        // 3、更新用户角色
        userRoleMapper.insert(user.getId(), user.getRoleIds());
    }
}